package com.sapient.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.sapient.DAO.LoginDAO;
import com.sapient.logic.Authenticate;


/**
 * Servlet implementation class Login
 */
@WebServlet("/Login")
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Login() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		HttpSession session=request.getSession();
		response.setContentType("text/html");

		String username=request.getParameter("user");
		String password=request.getParameter("pass");
		RequestDispatcher rd;

		Authenticate auth= new Authenticate();
		PrintWriter pw=response.getWriter();

		int valid =auth.authenticateDetails(username,password);

		String userRole;

		if(valid==0){
			request.getRequestDispatcher("login.jsp").include(request, response);  
			pw.write("<p align='center' style ='color:Red'><b>Username doesnt exist</b></p>");
			pw.write("<br>");

		}
		else if(valid==-1){



			request.getRequestDispatcher("login.jsp").include(request, response);  
			pw.write("<br>");
			pw.write("<p align='center' Style ='color:Red'><b> Username and Password doesnt match</b></p>");

		}

		else{
			session.setAttribute("User",username);
			
			userRole=auth.getUserRole(username);
			session.setAttribute("role", userRole);

			if(userRole.toUpperCase().equals("ADMIN")){
				rd=request.getRequestDispatcher("/Home.jsp");
				rd.forward(request, response);
			}
			else{
				rd=request.getRequestDispatcher("/HomeUser.jsp");
				rd.forward(request, response);
			}

		}


	}
}


